package com.jt.service.impl;

import com.jt.service.FileService;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/images.properties")
public class FileServiceImpl implements FileService {

    @Value("{image.rootDirPath}")
    private String rootDirPath;
    @Value("{image.urlPath}")
    private String urlPath;

    private static Set<String> imageTypeSet;
    static {
        imageTypeSet = new HashSet<>();
        imageTypeSet.add(".jpg");
        imageTypeSet.add(".png");
        imageTypeSet.add(".jpeg");
        imageTypeSet.add(".gif");
    }

    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        rootDirPath.trim();
        urlPath.trim();

        String originalFilename = uploadFile.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(lastIndexOf);
        fileType = fileType.toLowerCase();
        if(!imageTypeSet.contains(fileType)){
            return ImageVO.fail();
        }

        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width==0||height==0){
                return ImageVO.fail();
            }

            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDirPath = rootDirPath+dateDir;
            File dirFile = new File(fileDirPath);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            String uuid = UUID.randomUUID().toString().replace("-", "");
            String realFileName = uuid + fileType;

            String realFilePath = fileDirPath + realFileName;
            File realFile = new File(realFilePath);
            uploadFile.transferTo(realFile);

            String url = urlPath+dateDir+realFileName;
            return ImageVO.success(url, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }

    }

}
